package thu.cs.segroup.agent.behaviour;

import java.util.ArrayList;

import thu.cs.segroup.agent.Runner;
import thu.cs.segroup.agent.Coordinator;
import thu.cs.segroup.entity.RunnerState;
import thu.cs.segroup.util.Constants;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;

public class CoorGernerateRunnerBehav extends OneShotBehaviour{

	private int runnerNum;
	
	public CoorGernerateRunnerBehav(Agent agent, int _runnerNum) {
		super(agent);
		this.runnerNum = _runnerNum;
	}
	
	@Override
	public void action() {
		
		Coordinator coor = ((Coordinator)myAgent);
		AgentController controller;
		AgentContainer container = myAgent.getContainerController();
	/*	int num = -1;
		Object obj = coor.getProperty(Constants.COOR_RUNNER_NUMBER);
		if (obj == null) {
			num = 0;
		} else {
			num = (Integer)obj;
		}*/
		int init_size = coor.getRunners().size();
		for (int i = init_size; i < runnerNum + init_size; i++) {
			try {
				controller = container.createNewAgent("Runner" + i, Runner.class.getName(), new Object[]{coor.getRuleEngine()});
				coor.addRunner(new RunnerState("Runner" + i, Constants.STATE_RUNNER_FREE));
				controller.start();
			} catch (StaleProxyException e) {
				e.printStackTrace();
			}	
		}
		//coor.addProperty(Constants.COOR_RUNNER_NUMBER, num + runnerNum);
		myAgent.doWait(5000);
		
		ArrayList<String> des = new ArrayList<String>();
		des.add(myAgent.getName());
		myAgent.addBehaviour(new CommonSendStrMsgBehav("", des, myAgent, Constants.GENERATE_RUNNER_COMPLETE,
				ACLMessage.INFORM));
	}

}
